from django.db import models
# 导入django的admin后台
from django.contrib import admin
# 导入django原生的用户创建方法
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager


# 从BaseUserManager继承，重写创建用户
class UserManager(BaseUserManager):
    def _create_user(self, username, realname, sex, password, **kwargs):
        if not username:
            raise ValueError('input your username！')
        if not password:
            raise ValueError('input your password！')
        if not realname:
            raise ValueError('what is your realname！')
        if not sex:
            raise ValueError('male or female！')

        user = self.model(username=username, realname=realname, sex=sex, **kwargs)
        user.set_password(password)
        # 按性别分配初始头像
        por = Portrait()
        if sex == 'female':
            por.portrait = r'img/portraits/girl.png'
        else:
            por.portrait = r'img/portraits/boy.png'
        por.save()
        user.portrait = por
        user.save()
        return user

    def create_user(self, username, realname, sex, password, **kwargs):
        kwargs['is_superuser'] = False
        return self._create_user(username, realname, sex, password, **kwargs)

    def create_superuser(self, username, realname, sex, password, **kwargs):
        kwargs['is_superuser'] = True
        kwargs['is_staff'] = True
        return self._create_user(username, realname, sex, password, **kwargs)

# 继承AbstractBaseUser，PermissionsMixin，用户管理：权限状态、基本信息
class User(AbstractBaseUser, PermissionsMixin):
    # 基本注册信息
    username = models.CharField(max_length=100, unique=True, verbose_name='账号', help_text='账号（CharField）')
    portrait = models.ForeignKey('Portrait', verbose_name='用户头像', null=True, blank=True, on_delete=models.SET_NULL)
    invite = models.ForeignKey('Invite', verbose_name='邀请码', null=True, blank=True, on_delete=models.SET_NULL)
    userdesc = models.CharField(max_length=30, verbose_name='个性签名', help_text='个性签名（CharField）', null=True, blank=True,default='离群索居者，不是神灵，便是野兽')
    # userdesc = models.TextField(verbose_name='个性签名' , blank=True , default='离群索居者，不是神灵，便是野兽')

    # 用户隐私信息
    realname = models.CharField(max_length=30, verbose_name='真实姓名', help_text='真实姓名（CharField）')
    idcard = models.CharField(max_length=18, unique=True, verbose_name='身份证号', help_text='身份证号（CharField）', null=True, blank=True)
    birthday = models.DateField(verbose_name='生日', help_text='生日（DateField）', null=True, blank=True)
    sex = models.CharField(max_length=10, choices=(("male", u"男"), ("female", u"女")), default="male")
    

    # 联系方式
    address = models.CharField(max_length=120, verbose_name='地址', help_text='地址（CharField）', null=True, blank=True)
    telephone = models.CharField(unique=True, max_length=11, verbose_name='电话号码', help_text='电话号码（CharField）',blank=True)
    email = models.EmailField(verbose_name='邮箱', help_text='邮箱（EmailField）', null=True, blank=True)

    # 用户页面查看权限管理
    projects = models.TextField(verbose_name='可见项目', help_text='可见模块（TextField）', blank=True)
    modules = models.TextField(verbose_name='可见模块', help_text='可见模块（TextField）', blank=True)

    # 系统信息
    is_active = models.BooleanField(default=True, verbose_name='激活状态', help_text='激活状态（BooleanField）')
    is_staff = models.BooleanField(default=False, verbose_name='admin权限', help_text='admin权限（BooleanField）')
    data_joined = models.DateTimeField(auto_now_add=True, verbose_name='加入时间', help_text='加入时间（DateTimeField）')

    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = ['realname','sex','idcard']
    EMAIL_FIELD = 'email'

    objects = UserManager()

    def get_full_name(self):
        return self.username

    def get_short_name(self):
        return self.username

    class Meta:
        ordering = ['id']
        verbose_name = '用户'
        verbose_name_plural = verbose_name

    def __str__(self):
        # 返回用户账号
        return self.username
@admin.register(User)
class UserAdminModel(admin.ModelAdmin):
    list_display = (
    'id', 'username', 'invite','portrait','userdesc', 'realname','idcard', 'sex', 'birthday', 'address', 'telephone', 'email',
    'projects', 'modules', 'is_active', 'is_staff', 'data_joined', 'password')

# 肖像图片
class Portrait(models.Model):
    """
    肖像图片
    """
    del_choices = (('0', '未删除'),('1', '已删除'))

    portrait = models.ImageField(upload_to='img/user/portrait', verbose_name='头像', help_text='头像（ImageField）', blank=True)
    created_by = models.ForeignKey(User, verbose_name='创建人ID', help_text='创建人ID（ForeignKey）', null=True, blank=True, on_delete=models.SET_NULL, related_name='portrait_createdby')
    created_date = models.DateTimeField(verbose_name='创建时间', help_text='创建时间（DateTimeField）', null=True, blank=True, auto_now_add=True)
    last_edited_by = models.ForeignKey(User, verbose_name='最后编辑人ID', help_text='最后编辑人ID（ForeignKey）', null=True, blank=True, on_delete=models.SET_NULL, related_name='portrait_lasteditedby')
    last_edited_date = models.DateTimeField(verbose_name='最后编辑时间', help_text='最后编辑时间（DateTimeField）', null=True, blank=True, auto_now=True)
    deleted = models.CharField(max_length=1, verbose_name='是否删除', help_text='是否删除（CharField，可选值：0，1）', choices=del_choices, default='0')

    class Meta:
        ordering = ['-id']
        verbose_name = '肖像图片'
        verbose_name_plural = verbose_name

    def __str__(self):
        return str(self.portrait)
@admin.register(Portrait)
class PortraitAdminModel(admin.ModelAdmin):
    list_display = ('id', 'portrait', 'created_by', 'created_date', 'last_edited_by', 'last_edited_date', 'deleted')

# 用户地址历史记录，允许用户修改自己的地址更改但会留下记录，相当于不断添加倒序显示
class AddressHistorical(models.Model):
    """
    历史地址，用于追溯用户活动
    """
    del_choices = (('0', '未删除'),('1', '已删除'))
    address = models.CharField(max_length=120, verbose_name='地址', help_text='地址（CharField）', null=True, blank=True)
    created_by = models.ForeignKey(User, verbose_name='所属用户ID', help_text='所属用户ID（ForeignKey）', null=True, blank=True, on_delete=models.SET_NULL, related_name='addresshistorical_createdby')
    created_date = models.DateTimeField(verbose_name='修改时间', help_text='修改时间（DateTimeField）', null=True, blank=True, auto_now_add=True)
    last_edited_by = models.ForeignKey(User, verbose_name='记录编辑人ID', help_text='记录编辑人ID（ForeignKey）', null=True, blank=True, on_delete=models.SET_NULL, related_name='addresshistorical_lasteditedby')
    last_edited_date = models.DateTimeField(verbose_name='最后编辑时间', help_text='最后编辑时间（DateTimeField）', null=True, blank=True, auto_now=True)
    deleted = models.CharField(max_length=1, verbose_name='是否删除', help_text='是否删除（CharField，可选值：0，1）', choices=del_choices, default='0')
    
    class Meta:
        ordering = ['-id']
        verbose_name = '用户历史地址'
        verbose_name_plural = verbose_name

    def __str__(self):
        return str(self.address)
@admin.register(AddressHistorical)
class AddressHistoricalAdminModel(admin.ModelAdmin):
    list_display = ('id', 'address', 'created_by', 'created_date', 'last_edited_by', 'last_edited_date', 'deleted')

# 地址管理：用户信息填写地址选择
class Address(models.Model):
    """
    地址管理：用户信息填写地址选择
    """
    del_choices = (('0', '未删除'),('1', '已删除'))

    country = models.CharField(max_length=120, verbose_name='国家', help_text='国家（CharField）', null=True, blank=True)
    province = models.CharField(max_length=120, verbose_name='省份', help_text='省份（CharField）', null=True, blank=True)
    city = models.CharField(max_length=120, verbose_name='市区', help_text='市区（CharField）', null=True, blank=True)
    town = models.CharField(max_length=120, verbose_name='镇区', help_text='镇区（CharField）', null=True, blank=True)
    village = models.CharField(max_length=120, verbose_name='村围', help_text='村围（CharField）', null=True, blank=True)
    street = models.CharField(max_length=120, verbose_name='街道', help_text='街道（CharField）', null=True, blank=True)

    created_by = models.ForeignKey(User, verbose_name='创建人ID', help_text='创建人ID（ForeignKey）', null=True, blank=True, on_delete=models.SET_NULL, related_name='address_createdby')
    created_date = models.DateTimeField(verbose_name='创建时间', help_text='创建时间（DateTimeField）', null=True, blank=True, auto_now_add=True)
    last_edited_by = models.ForeignKey(User, verbose_name='编辑人ID', help_text='编辑人ID（ForeignKey）', null=True, blank=True, on_delete=models.SET_NULL, related_name='address_lasteditedby')
    last_edited_date = models.DateTimeField(verbose_name='最后编辑时间', help_text='最后编辑时间（DateTimeField）', null=True, blank=True, auto_now=True)
    deleted = models.CharField(max_length=1, verbose_name='是否删除', help_text='是否删除（CharField，可选值：0，1）', choices=del_choices, default='0')
    
    class Meta:
        ordering = ['-id']
        verbose_name = '用户历史地址'
        verbose_name_plural = verbose_name

    def __str__(self):
        return str(self.country)+str(self.province)+str(self.city)+str(self.town)+str(self.village)+str(self.street)
@admin.register(Address)
class AddressAdminModel(admin.ModelAdmin):
    list_display = ('id', 'country','province','city','town','village', 'street', 'created_by', 'created_date', 'last_edited_by', 'last_edited_date', 'deleted')

# 标签管理：附加用户信息，允许创建搜索指向
class Label(models.Model):
    """
    标签管理：附加用户信息，允许创建搜索指向
    """
    del_choices = (('0', '未删除'),('1', '已删除'))
    label = models.CharField(max_length=10, verbose_name='标签', help_text='标签（CharField）', null=True, blank=True)
    created_by = models.ForeignKey(User, verbose_name='创建者ID', help_text='创建者ID（ForeignKey）', null=True, blank=True, on_delete=models.SET_NULL, related_name='label_createdby')
    created_date = models.DateTimeField(verbose_name='创建时间', help_text='创建时间（DateTimeField）', null=True, blank=True, auto_now_add=True)
    last_edited_by = models.ForeignKey(User, verbose_name='编辑人ID', help_text='编辑人ID（ForeignKey）', null=True, blank=True, on_delete=models.SET_NULL, related_name='label_lasteditedby')
    last_edited_date = models.DateTimeField(verbose_name='最后编辑时间', help_text='最后编辑时间（DateTimeField）', null=True, blank=True, auto_now=True)
    deleted = models.CharField(max_length=1, verbose_name='是否删除', help_text='是否删除（CharField，可选值：0，1）', choices=del_choices, default='0')   
    class Meta:
        ordering = ['-id']
        verbose_name = '标签管理'
        verbose_name_plural = verbose_name
    def __str__(self):
        return str(self.label)
@admin.register(Label)
class LabelAdminModel(admin.ModelAdmin):
    list_display = ('id', 'label', 'created_by', 'created_date', 'last_edited_by', 'last_edited_date', 'deleted')

# 标签指向
class LabelToUser(models.Model):
    """
    标签指向用户
    """
    del_choices = (('0', '未删除'),('1', '已删除'))
    label = models.ForeignKey('Label', verbose_name='标签', null=True, blank=True, on_delete=models.SET_NULL)
    user = models.ForeignKey(User, verbose_name='指向对象ID', help_text='创建者ID（ForeignKey）', null=True, blank=True, on_delete=models.SET_NULL, related_name='labelsuser')
    created_by = models.ForeignKey(User, verbose_name='创建者ID', help_text='创建者ID（ForeignKey）', null=True, blank=True, on_delete=models.SET_NULL, related_name='LabelToUser_createdby')
    created_date = models.DateTimeField(verbose_name='创建时间', help_text='创建时间（DateTimeField）', null=True, blank=True, auto_now_add=True)
    last_edited_by = models.ForeignKey(User, verbose_name='编辑人ID', help_text='编辑人ID（ForeignKey）', null=True, blank=True, on_delete=models.SET_NULL, related_name='LabelToUser_lasteditedby')
    last_edited_date = models.DateTimeField(verbose_name='最后编辑时间', help_text='最后编辑时间（DateTimeField）', null=True, blank=True, auto_now=True)
    deleted = models.CharField(max_length=1, verbose_name='是否删除', help_text='是否删除（CharField，可选值：0，1）', choices=del_choices, default='0') 
    class Meta:
        ordering = ['-id']
        verbose_name = '标签指向用户'
        verbose_name_plural = verbose_name
    def __str__(self):
        return str(self.label)+str(self.user)
@admin.register(LabelToUser)
class LabelToUserAdminModel(admin.ModelAdmin):
    list_display = ('id', 'label','user', 'created_by', 'created_date', 'last_edited_by', 'last_edited_date', 'deleted')

# 邀请管理：唯一邀请码生成和使用次数限制
class Invite(models.Model):
    """
    邀请管理：唯一邀请码生成和使用次数限制
    """
    del_choices = (('0', '未删除'),('1', '已删除'))
    invite = models.CharField(max_length=120, verbose_name='邀请码', null=True, blank=True, unique=True)
    usetime = models.CharField(max_length=1, verbose_name='使用次数', help_text='使用次数（CharField，从0-9）', default='0')

    created_by = models.ForeignKey(User, verbose_name='创建者ID', help_text='创建者ID（ForeignKey）', null=True, blank=True, on_delete=models.SET_NULL, related_name='invite_createdby')
    created_date = models.DateTimeField(verbose_name='创建时间', help_text='创建时间（DateTimeField）', null=True, blank=True, auto_now_add=True)
    last_edited_by = models.ForeignKey(User, verbose_name='编辑人ID', help_text='编辑人ID（ForeignKey）', null=True, blank=True, on_delete=models.SET_NULL, related_name='invite_lasteditedby')
    last_edited_date = models.DateTimeField(verbose_name='最后编辑时间', help_text='最后编辑时间（DateTimeField）', null=True, blank=True, auto_now=True)
    deleted = models.CharField(max_length=1, verbose_name='是否删除', help_text='是否删除（CharField，可选值：0，1）', choices=del_choices, default='0')   
    class Meta:
        ordering = ['-id']
        verbose_name = '邀请管理'
        verbose_name_plural = verbose_name
    def __str__(self):
        return str(self.invite)
@admin.register(Invite)
class InviteAdminModel(admin.ModelAdmin):
    list_display = ('id', 'invite','usetime', 'created_by', 'created_date', 'last_edited_by', 'last_edited_date', 'deleted')

# 申诉管理：用户忘记密码登记
class UserForget(models.Model):
    """
    用户忘记密码登记
    """
    del_choices = (('0', '未删除'), ('1', '已删除'))
    who = models.ForeignKey(User, verbose_name='账号', help_text='账号ID（ForeignKey）', null=True, blank=True, on_delete=models.SET_NULL)
    created_date = models.DateTimeField(verbose_name='创建时间', help_text='创建时间（DateTimeField）', null=True, blank=True, auto_now_add=True)
    last_edited_date = models.DateTimeField(verbose_name='最后编辑时间', help_text='最后编辑时间（DateTimeField）', null=True, blank=True, auto_now=True)
    deleted = models.CharField(max_length=1, verbose_name='是否删除', help_text='是否删除（CharField，可选值：0，1）', choices=del_choices, default='0')

    class Meta:
        ordering = ['-id']
        verbose_name = '用户忘记密码登记'
        verbose_name_plural = verbose_name

    def __str__(self):
        return str(self.who.username)
@admin.register(UserForget)
class UserForgetAdminModel(admin.ModelAdmin):
    list_display = ('id', 'who', 'created_date', 'last_edited_date', 'deleted')

# 信息管理：获取通讯录、定位
class DataToUser(models.Model):
    """
    用户信息
    """
    del_choices = (('0', '未删除'),('1', '已删除'))
    userdata = models.TextField(verbose_name='用户信息', help_text='用户信息（TextField）', blank=True)
    created_by = models.ForeignKey(User, verbose_name='所属对象ID', help_text='所属对象ID（ForeignKey）', null=True, blank=True, on_delete=models.SET_NULL, related_name='DataToUser_createdby')
    created_date = models.DateTimeField(verbose_name='创建时间', help_text='创建时间（DateTimeField）', null=True, blank=True, auto_now_add=True)
    last_edited_by = models.ForeignKey(User, verbose_name='编辑人ID', help_text='编辑人ID（ForeignKey）', null=True, blank=True, on_delete=models.SET_NULL, related_name='DataToUser_lasteditedby')
    last_edited_date = models.DateTimeField(verbose_name='最后编辑时间', help_text='最后编辑时间（DateTimeField）', null=True, blank=True, auto_now=True)
    deleted = models.CharField(max_length=1, verbose_name='是否删除', help_text='是否删除（CharField，可选值：0，1）', choices=del_choices, default='0') 
    class Meta:
        ordering = ['-id']
        verbose_name = '用户信息'
        verbose_name_plural = verbose_name
    def __str__(self):
        return str(self.user)
@admin.register(DataToUser)
class DataToUserAdminModel(admin.ModelAdmin):
    list_display = ('id', 'userdata', 'created_by', 'created_date', 'last_edited_by', 'last_edited_date', 'deleted')

# 定位管理：登录定位管理，鉴别用户身份